package com.example.demo.listen;

import com.example.demo.common.ConnectionContainer;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yuaneg 2018/12/12
 */
@Slf4j
@Component
public class TxTransactionListen {

    @Getter
    @Setter
    private Map<String, ConnectionContainer> connectionMap = new ConcurrentHashMap<>();

    public void transactionListenSuccess(String transactionId) throws SQLException {
        if (null != connectionMap.get(transactionId)) {
            Connection connection = connectionMap.get(transactionId).getConnection();
            if (!connection.isClosed()) {
                connection.commit();
                connection.close();
                log.info("事物提交成功");
                connectionMap.remove(transactionId);
            } else {
                throw new RuntimeException("连接已关闭");
            }
        } else {
            log.debug("此节点未找到事物connection");
        }
    }


    public void transactionListenFail(String transactionId) throws SQLException {
        if (null != connectionMap.get(transactionId)) {
            Connection connection = connectionMap.get(transactionId).getConnection();
            if (!connection.isClosed()) {
                connection.rollback();
                connection.close();
                log.info("事物回滚成功");
                connectionMap.remove(transactionId);
            } else {
                throw new RuntimeException("连接已关闭");
            }
        } else {
            log.debug("此节点未找到事物connection");
        }
    }

    public void addConnection(String key, ConnectionContainer connectionContainer) {
        connectionMap.put(key, connectionContainer);
    }


}
